//------------------------------------------------------------------------------
// <pcdd-entitiy>
//     彩票主流业务类库
//     期号业务对象
// </pcdd-entitiy>
//------------------------------------------------------------------------------ 

using CL.Enum.Common;
using CL.Enum.Common.Lottery;
using CL.Game.DAL;
using CL.Game.Entity;
using CL.Json.Entity.WebAPI;
using CL.Redis.BLL;
using CL.Tools.Common;
using CL.Tools.TicketInterface;
using CL.View.Entity.Game;
using CL.View.Entity.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;

namespace CL.Game.BLL
{

    /// <summary>
    /// IsusesBLL 业务
    /// </summary>
    public class IsusesBLL
    {
        IsusesDAL dal = new IsusesDAL(DbConnectionEnum.CaileGame);

        Log log = new Log("IsusesBLL");

        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public bool Exists(long IsuseID)
        {
            return dal.Exists(IsuseID);
        }
        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public bool Exists(string IsuseName, int LotteryCode)
        {
            return dal.Exists(IsuseName, LotteryCode);
        }
        /// <summary>
        /// 根据彩种编号查询期号集
        /// </summary>
        /// <param name="LotteryCode"></param>
        /// <returns></returns>
        public IsusesEntity QueryEntitysByLotteryCode(int LotteryCode, string IsuseName)
        {
            return dal.QueryEntitysByLotteryCode(LotteryCode, IsuseName);
        }
        /// <summary>
        /// 获取彩种最近一次的期号
        /// </summary>
        /// <param name="LotteryCode"></param>
        /// <returns></returns>
        public IsusesEntity QueryEntity(long IsuseID)
        {
            return dal.QueryEntity(IsuseID);
        }
        /// <summary>
        /// 获取彩种最近一次的期号
        /// </summary>
        /// <param name="LotteryCode"></param>
        /// <returns></returns>
        public IsusesEntity QueryEntitysLastIsues(int LotteryCode)
        {
            return dal.QueryEntitysLastIsues(LotteryCode);
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool ModifyEntity(IsusesEntity entity)
        {
            return dal.ModifyEntity(entity) > 0;
        }
        /// <summary>
        /// 插入对象集
        /// </summary>
        /// <param name="Entitys"></param>
        /// <returns></returns>
        public bool InsertEntity(List<IsusesEntity> Entitys)
        {
            return dal.InsertEntity(Entitys);
        }
        /// <summary>
        /// 查询当期开期数据
        /// </summary>
        /// <param name="LotteryCode"></param>
        /// <returns></returns>
        public udv_IsuseInfo QueryLotteryCurrIsuses(int LotteryCode)
        {
            return dal.QueryLotteryCurrIsuses(LotteryCode);
        }
        /// <summary>
        /// 查询当期开期数据
        /// </summary>
        /// <param name="LotteryCode"></param>
        /// <returns></returns>
        public udv_IsuseInfo QueryLotteryCurrIsuses(int LotteryCode, string IsuseName)
        {
            return dal.QueryLotteryCurrIsuses(LotteryCode, IsuseName);
        }
        /// <summary>
        /// 追号时查询期号信息
        /// </summary>
        /// <param name="LotteryCode"></param>
        /// <returns></returns>
        public List<IsusesEntity> QueryChaseTasksIsuses(int TopCount, int LotteryCode)
        {
            return dal.QueryChaseTasksIsuses(TopCount, LotteryCode);
        }
        /// <summary>
        /// 获取遗漏的期号记录
        /// </summary>
        /// <param name="LotteryCode"></param>
        /// <returns></returns>
        public List<IsusesEntity> QueryNumEmpty(int LotteryCode, string DateDay = null)
        {
            return dal.QueryNumEmpty(LotteryCode, DateDay);
        }


        /// <summary>
        /// 生产彩种期号
        /// </summary>
        /// <param name="LotteryCode"></param>
        /// <param name="Date"></param>
        /// <param name="Days"></param>
        /// <returns></returns>
        public int AddIsuseAdd(int LotteryCode, string sDate, int Days)
        {
            return dal.AddIsuseAdd(LotteryCode, sDate, Days);
        }
        /// <summary>
        /// 生产彩种期号
        /// </summary>
        /// <param name="IsseuName">开始期号</param>
        /// <param name="LotteryCode">彩种</param>
        /// <param name="Date">日期</param>
        /// <param name="Days">生产天数</param>
        /// <returns></returns>
        public int AddIssueLuck(int IsseuName, int LotteryCode, string sDate, int Days)
        {
            return dal.AddIssueLuck(IsseuName, LotteryCode, sDate, Days);
        }
        /// <summary>
        /// 生产彩种期号
        /// </summary>
        /// <param name="LotteryCode"></param>
        /// <param name="Date"></param>
        /// <param name="Days"></param>
        /// <returns></returns>
        public int GenerateIssue(int LotteryCode, string sDate, int Days)
        {
            return dal.GenerateIssue(LotteryCode, sDate, Days);
        }
        /// <summary>
        /// 生产彩种期号福利彩如：双色球、大乐透
        /// </summary>
        /// <param name="LotteryCode"></param>
        /// <param name="sDate"></param>
        /// <returns></returns>
        public int AddIsuseAddFC(int LotteryCode, string sDate)
        {
            return dal.AddIsuseAddFC(LotteryCode, sDate);
        }
        /// <summary>
        /// 分页获取数据列表
        /// </summary>
        public List<IsusesEntity> QueryListByPage(int LotteryCode, string date, string strName, string orderby, int pageSize, int pageIndex, ref int recordCount)
        {
            return dal.QueryListByPage(LotteryCode, date, strName, orderby, pageSize, pageIndex, ref recordCount);
        }
        /// <summary>
        /// 添加采集的数据记录
        /// </summary>
        /// <returns></returns>
        public bool AddLotteryOpenNumber(int LotteryCode, string IsuseName, string OpenNumber, DateTime StartTime, DateTime EndTime, DateTime OpenTime, ref string ReturnDescription)
        {
            return dal.AddLotteryOpenNumber(LotteryCode, IsuseName, OpenNumber, StartTime, EndTime, OpenTime, ref ReturnDescription);
        }
        /// <summary>
        /// 录入开奖结果
        /// </summary>
        /// <param name="LotteryCode"></param>
        /// <param name="IsuseName"></param>
        /// <param name="OpenNumber"></param>
        /// <param name="OpenTime"></param>
        /// <param name="ReturnDescription"></param>
        /// <returns></returns>
        public bool EnteringDrawResults(int LotteryCode, string IsuseName, string OpenNumber, DateTime OpenTime, ref string ReturnDescription)
        {
            return dal.EnteringDrawResults(LotteryCode, IsuseName, OpenNumber, OpenTime, ref ReturnDescription);
        }
        /// <summary>
        /// 获取最新开售期号
        /// </summary>
        /// <returns></returns>
        public IsusesEntity QueryNewSaleIsuses(int LotteryCode)
        {
            return dal.QueryNewSaleIsuses(LotteryCode);
        }

        /// <summary>
        /// 走势图查询列表
        /// </summary>
        /// <param name="LotteryCode">彩种编号</param>
        /// <param name="IsuseName">期号</param>
        /// <returns></returns>
        public List<IsusesEntity> QueryLotTrendChart(int LotteryCode, int TOPCount, string IsuseName)
        {
            List<IsusesEntity> Entitys = new BusinessRedis().LotTrendChartRedis(LotteryCode, IsuseName, TOPCount);
            if (Entitys == null || Entitys.Count == 0)
            {
                Entitys = dal.QueryLotTrendChart(LotteryCode, TOPCount);
                new BusinessRedis().LotTrendChartRedis(LotteryCode, IsuseName, Entitys, TOPCount);
            }
            return Entitys;
        }
        /// <summary>
        /// 获取封盘期号
        /// 只使用低频彩
        /// </summary>
        /// <returns></returns>
        public IsusesEntity QueryEntertainedIsuses(int LotteryCode)
        {
            return dal.QueryEntertainedIsuses(LotteryCode);
        }
        /// <summary>
        /// 开奖大厅数据查询
        /// </summary>
        /// <returns></returns>
        public List<IsusesEntity> OpenAwardHall()
        {
            var Entitys = new BusinessRedis().Query_OpenAwardHall();
            if (Entitys == null || Entitys.Count == 0)
            {
                Entitys = dal.OpenAwardHall();
                if (Entitys != null && Entitys.Count > 0)
                    new BusinessRedis().Save_OpenAwardHall(Entitys);
            }
            return Entitys;
        }

        /// <summary>
        /// 查询当前期的上一期是否开奖
        /// </summary>
        /// <param name="LotteryCode"></param>
        /// <returns></returns>
        public IsusesEntity QueryLastIsuseInfo(int LotteryCode)
        {
            return dal.QueryLastIsuseInfo(LotteryCode);
        }
        /// <summary>
        /// 查询上一期的投注用户
        /// </summary>
        /// <param name="LotteryCode"></param>
        /// <returns></returns>
        public List<UsersEntity> QueryLastOpenUsers(int LotteryCode)
        {
            return dal.QueryLastOpenUsers(LotteryCode);
        }
        /// <summary>
        /// 查询开奖记录
        /// </summary>
        /// <param name="LotteryCode"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        public List<IsusesEntity> QueryOfLotteryRecord(int LotteryCode, int pageIndex, int pageSize)
        {
            return dal.QueryOfLotteryRecord(LotteryCode, pageIndex, pageSize);
        }


        #region 自定义方法
        /// <summary>
        /// 当前期信息
        /// </summary>
        /// <param name="Token"></param>
        /// <param name="LotteryCode"></param>
        /// <returns></returns>
        public CurrentIsuseInfoResult CurrentIsuseInfo(int LotteryCode)
        {
            CurrentIsuseInfoResult result = null;
            try
            {
                int RecCode = (int)ResultCode.NullData;
                CurrentIsuseInfoEntity isuseData = null;
                TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 8, 0, 0, 0);
                var Entity = new BusinessRedis().CurrentIsuseRedis(LotteryCode);
                if (Entity == null)
                {
                    Entity = this.QueryLotteryCurrIsuses(LotteryCode);
                    if (Entity == null)
                    {
                        if (LotteryCode == (int)LotteryInfo.SD11X5)
                        {
                            //预售
                            Entity = this.QueryLotteryCurrIsuses(LotteryCode, string.Empty);
                            if (Entity == null)
                                RecCode = (int)ResultCode.NullData;
                            else
                            {
                                #region 验证是否当日最后一期  最后一期则预售 否则就等待
                                int total = 0;
                                int currentisuse = 0;
                                    string[] arr_1 = (Entity.IntervalType ?? "").Split('@');
                                    if (arr_1.Length >= 3)
                                        total = Convert.ToInt32(arr_1[2]);
                                    if (LotteryCode == (int)LotteryInfo.CQSSC)
                                        currentisuse = Convert.ToInt32(Entity.IsuseName.Substring(Entity.IsuseName.Length - 3, 3));
                                    else
                                        currentisuse = Convert.ToInt32(Entity.IsuseName.Substring(Entity.IsuseName.Length - 2, 2));
                                    if (currentisuse <= total && currentisuse != 1)
                                        return new CurrentIsuseInfoResult()
                                        {
                                            Code = (int)ResultCode.NullData,
                                            Msg = Common.GetDescription(ResultCode.NullData)
                                        };
                                #endregion
                                var StartTime = Entity.StartTime;
                                if (Entity.PresellTime > 0)
                                    StartTime = Convert.ToDateTime(Entity.StartTime).AddMinutes(-Entity.PresellTime);
                                var EndTime = Entity.StartTime;
                                Entity.EndTime = EndTime;
                                Entity.StartTime = DateTime.Now;
                                int totalIsuse = 0;
                                if (LotteryCode != 801 && LotteryCode != 901)
                                {
                                    string[] arr_2 = (Entity.IntervalType ?? "").Split('@');
                                    if (arr_2.Length >= 3)
                                    {
                                        totalIsuse = Convert.ToInt32(arr_2[2]);
                                    }
                                }
                                RecCode = (int)ResultCode.IsPresell;
                                isuseData = new CurrentIsuseInfoEntity()
                                {
                                    IsuseNum = Entity.IsuseName,
                                    TotalIsuse = totalIsuse,
                                    BeginTime = Entity.StartTime.ToString("yyyyMMddHHmmss"),
                                    EndTime = Entity.EndTime.ToString("yyyyMMddHHmmss"),
                                    ServerTime = Convert.ToInt64(ts.TotalMilliseconds).ToString()
                                };
                            }
                        }
                    }
                    else
                    {
                        #region ---------- 读取接口期号数据 重庆时时彩 (彩种华阳接口期次号规则与官网期次号规则不同) ---------- 
                        if (LotteryCode == (int)LotteryInfo.CQSSC)
                        {
                            try
                            {
                                XmlNode Node = Utils.QueryConfigNode("root/interface");
                                if (Node != null)
                                {
                                    XmlNodeList XmlList = Node.SelectNodes("item");
                                    foreach (XmlNode xml in XmlList)
                                    {
                                        if (Convert.ToInt32(xml.SelectSingleNode("systemlotterycode").InnerText) == LotteryCode)
                                        {
                                            InterfaceBase InterTicker = new InterfaceBase()[xml];
                                            udv_ParaIsuse ParaIsuse = new udv_ParaIsuse()
                                            {
                                                LotteryID = Entity.LotteryCode.ToString(),
                                                Issue = Entity.IsuseName.Substring(2, Entity.IsuseName.Length - 2)
                                            };
                                            udv_ResultIssue ResModel = InterTicker.GetIsuseInfo(ParaIsuse);
                                            if (ResModel.ErrorCode == "0")
                                            {
                                                Entity.StartTime = DateTime.Parse(ResModel.StartTime);
                                                Entity.EndTime = DateTime.Parse(ResModel.EndTime);
                                                #region 更新对象
                                                var et = this.QueryEntity(Entity.IsuseID);
                                                et.StartTime = DateTime.Parse(ResModel.StartTime);
                                                et.EndTime = DateTime.Parse(ResModel.EndTime);
                                                this.ModifyEntity(et);
                                                #endregion
                                                #region 更新下一期对象
                                                int IsuseNum = Convert.ToInt32(Entity.IsuseName.Substring(9, Entity.IsuseName.Length - 9)) + 1;
                                                string Day = Entity.IsuseName.Substring(0, 8);
                                                string[] arr = (Entity.IntervalType ?? "").Split('@');
                                                if (Convert.ToInt32(arr[2]) >= IsuseNum)
                                                {
                                                    string CombinationIsuseName = string.Format("{0}{1}", Day, IsuseNum.ToString().PadLeft(3, '0'));
                                                    var NextIssueEntity = this.QueryEntitysByLotteryCode(LotteryCode, CombinationIsuseName);
                                                    if (NextIssueEntity != null)
                                                    {
                                                        NextIssueEntity.StartTime = Entity.EndTime;
                                                        this.ModifyEntity(NextIssueEntity);
                                                    }
                                                }
                                                #endregion
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                log.Write("华阳接口期次号规则与官网期次号规则不同错误：" + ex.StackTrace, true);
                            }
                        }
                        #endregion
                        var EndTime = Entity.EndTime;
                        var StartTime = Entity.StartTime;
                        if (Entity.AdvanceEndTime > 0)
                            EndTime = Convert.ToDateTime(Entity.EndTime).AddMinutes(-Entity.AdvanceEndTime);
                        if (Entity.PresellTime > 0)
                            StartTime = Convert.ToDateTime(Entity.StartTime).AddMinutes(-Entity.PresellTime);
                        Entity.EndTime = EndTime;
                        Entity.StartTime = StartTime;
                        new BusinessRedis().CurrentIsuseRedis(Entity, EndTime); //redis存储
                        int totalIsuse = 0;
                        if (LotteryCode != 801 && LotteryCode != 901)
                        {
                            string[] arr = (Entity.IntervalType ?? "").Split('@');
                            if (arr.Length >= 3)
                            {
                                totalIsuse = Convert.ToInt32(arr[2]);
                            }
                        }
                        RecCode = (int)ResultCode.Success;
                        isuseData = new CurrentIsuseInfoEntity()
                        {
                            IsuseNum = Entity.IsuseName,
                            TotalIsuse = totalIsuse,
                            BeginTime = Entity.StartTime.ToString("yyyyMMddHHmmss"),
                            EndTime = Entity.EndTime.ToString("yyyyMMddHHmmss"),
                            ServerTime = Convert.ToInt64(ts.TotalMilliseconds).ToString()
                        };
                    }
                }
                else
                {
                    int totalIsuse = 0;
                    if (LotteryCode != 801 && LotteryCode != 901)
                    {
                        string[] arr = (Entity.IntervalType ?? "").Split('@');
                        if (arr.Length >= 3)
                        {
                            totalIsuse = Convert.ToInt32(arr[2]);
                        }
                    }
                    RecCode = (int)ResultCode.Success;
                    isuseData = new CurrentIsuseInfoEntity()
                    {
                        IsuseNum = Entity.IsuseName,
                        TotalIsuse = totalIsuse,
                        BeginTime = Entity.StartTime.ToString("yyyyMMddHHmmss"),
                        EndTime = Entity.EndTime.ToString("yyyyMMddHHmmss"),
                        ServerTime = Convert.ToInt64(ts.TotalMilliseconds).ToString()
                    };
                }
                result = new CurrentIsuseInfoResult()
                {
                    Code = RecCode,
                    Msg = Common.GetDescription((ResultCode)RecCode),
                    Data = RecCode != (int)ResultCode.Success ? null : isuseData
                };
            }
            catch (Exception ex)
            {
                log.Write("当前期信息错误[CurrentIsuseInfo]：" + ex.StackTrace, true);
                result = new CurrentIsuseInfoResult()
                {
                    Code = (int)ResultCode.SystemBusy,
                    Msg = Common.GetDescription(ResultCode.SystemBusy),
                    Data = null
                };
            }

            return result;
        }

        /// <summary>
        /// 开奖列表
        /// </summary>
        /// <param name="Token"></param>
        /// <param name="LotteryCode"></param>
        /// <param name="PageNumber"></param>
        /// <param name="RowsPerPage"></param>
        /// <returns></returns>
        public OfLotteryResult OfLotteryRecord(int LotteryCode, int PageNumber, int RowsPerPage)
        {
            OfLotteryResult result = null;
            try
            {
                int RecCode = (int)ResultCode.Success;
                var Entitys = new BusinessRedis().OfLotteryRecordRedis(LotteryCode, PageNumber, RowsPerPage);
                if (Entitys == null || Entitys.Count == 0 || Entitys.Count != PageNumber)
                {
                    //对比db
                    var IsuseEntity = this.QueryOfLotteryRecord(LotteryCode, PageNumber, RowsPerPage);
                    if (IsuseEntity != null)
                        Entitys = IsuseEntity.Select(s => new OfLotteryEntity()
                        {
                            IsuseNum = s.IsuseName,
                            LotteryCode = LotteryCode,
                            Number = this.HandleOpenNumber(LotteryCode, s.OpenNumber),
                            OpenTime = s.OpenTime == null ? "" : (Convert.ToDateTime(s.OpenTime)).ToString("yyyyMMddHHmmss")
                        }).ToList();
                    else
                        RecCode = (int)ResultCode.NullData;
                }
                else
                    Entitys = Entitys.Select(s => new OfLotteryEntity()
                    {
                        IsuseNum = s.IsuseNum,
                        LotteryCode = s.LotteryCode,
                        Number = this.HandleOpenNumber(LotteryCode, s.Number),
                        OpenTime = s.OpenTime
                    }).ToList();
                result = new OfLotteryResult()
                {
                    Code = RecCode,
                    Msg = Common.GetDescription((ResultCode)RecCode),
                    Data = RecCode != (int)ResultCode.Success ? null : Entitys
                };
            }
            catch (Exception ex)
            {
                log.Write("开奖列表错误[OfLotteryRecord]：" + ex.StackTrace, true);
                result = new OfLotteryResult()
                {
                    Code = (int)ResultCode.Error,
                    Msg = Common.GetDescription(ResultCode.Error),
                    Data = null
                };
            }
            return result;
        }
        public string HandleOpenNumber(int LotterCode, string OpenNumber)
        {
            if (!string.IsNullOrEmpty(OpenNumber))
            {
                if (LotterCode == (int)LotteryInfo.JND28 && OpenNumber.Split(' ').Length == 20)
                {
                    //从小到大的顺序依次排列开奖号码
                    //1 第2/5/8/11/14/17位数字
                    //2 第3/6/9/12/15/18位数字
                    //3 第4/7/10/13/16/19位数字
                    int[] OpenNum = OpenNumber.Split(' ').Select(s => Convert.ToInt32(s)).OrderBy(o => o).ToArray();
                    int[] OpenNum1 = new int[] { OpenNum[1], OpenNum[4], OpenNum[7], OpenNum[10], OpenNum[13], OpenNum[16] };
                    int[] OpenNum2 = new int[] { OpenNum[2], OpenNum[5], OpenNum[8], OpenNum[11], OpenNum[14], OpenNum[17] };
                    int[] OpenNum3 = new int[] { OpenNum[3], OpenNum[6], OpenNum[9], OpenNum[12], OpenNum[15], OpenNum[18] };
                    //开奖号码和值
                    int[] OpenNumSum = new int[] { Convert.ToInt32(OpenNum1.Sum().ToString().Substring(OpenNum1.Sum().ToString().Length - 1, 1)),
                                               Convert.ToInt32(OpenNum2.Sum().ToString().Substring(OpenNum2.Sum().ToString().Length - 1, 1)),
                                               Convert.ToInt32(OpenNum3.Sum().ToString().Substring(OpenNum3.Sum().ToString().Length - 1, 1))};
                    return string.Format("{0} + {1} + {2} = {3} ", OpenNumSum[0], OpenNumSum[1], OpenNumSum[2], OpenNumSum.Sum());
                }
                else if (LotterCode == (int)LotteryInfo.XY28 && OpenNumber.Split(' ').Length == 20)
                {
                    //从小到大的顺序依次排列开奖号码
                    //取1-6位开奖号码相加的和值尾作为幸运28第1位开奖号码
                    //取7-12位开奖号码相加的和值尾作为幸运28第2位开奖号码
                    //取13-18位开奖号码相加的和值尾作为幸运28第3位开奖号码
                    int[] OpenNum = OpenNumber.Split(' ').Select(s => Convert.ToInt32(s)).OrderBy(o => o).ToArray();
                    int[] OpenNum1 = new int[] { OpenNum[0], OpenNum[1], OpenNum[2], OpenNum[3], OpenNum[4], OpenNum[5] };
                    int[] OpenNum2 = new int[] { OpenNum[6], OpenNum[7], OpenNum[8], OpenNum[9], OpenNum[10], OpenNum[11] };
                    int[] OpenNum3 = new int[] { OpenNum[12], OpenNum[13], OpenNum[14], OpenNum[15], OpenNum[16], OpenNum[17] };
                    //开奖号码和值
                    int[] OpenNumSum = new int[] { Convert.ToInt32(OpenNum1.Sum().ToString().Substring(OpenNum1.Sum().ToString().Length - 1, 1)),
                                               Convert.ToInt32(OpenNum2.Sum().ToString().Substring(OpenNum2.Sum().ToString().Length - 1, 1)),
                                               Convert.ToInt32(OpenNum3.Sum().ToString().Substring(OpenNum3.Sum().ToString().Length - 1, 1))};
                    return string.Format("{0} + {1} + {2} = {3} ", OpenNumSum[0], OpenNumSum[1], OpenNumSum[2], OpenNumSum.Sum());

                }
                else
                    return OpenNumber;
            }
            else
                return OpenNumber;
        }

        /// <summary>
        /// 开奖详情
        /// </summary>
        /// <param name="Token"></param>
        /// <param name="LotteryCode"></param>
        /// <param name="IsuseNum"></param>
        /// <returns></returns>
        public OfLotteryDetailResult OfLotteryDetail(int LotteryCode, string IsuseNum)
        {
            OfLotteryDetailResult result = null;
            try
            {
                int RecCode = (int)ResultCode.Success;
                var Entity = new BusinessRedis().OfLotteryDetailRedis(LotteryCode, IsuseNum);
                if (Entity == null)
                {
                    var IssueEntity = new IsusesBLL().QueryEntitysByLotteryCode(LotteryCode, IsuseNum);
                    if (IssueEntity != null)
                    {
                        Entity = new OfLotteryDetailEntity();
                        Entity.EndTime = IssueEntity.EndTime;
                        Entity.IsuseNum = IsuseNum;
                        Entity.LotteryCode = LotteryCode;
                        Entity.OpenLotUser = IssueEntity.OpenOperatorID;
                        Entity.OpenNumber = IssueEntity.OpenNumber;
                        Entity.OpenTime = IssueEntity.OpenTime == null ? "" : Convert.ToDateTime(IssueEntity.OpenTime).ToString("yyyyMMddHHmmss");
                        Entity.TotalSales = IssueEntity.TotalSales;
                        Entity.WinRollover = string.IsNullOrEmpty(IssueEntity.WinRollover) == true ? 0 : Convert.ToInt64(IssueEntity.WinRollover);
                    }
                    else
                        RecCode = (int)ResultCode.NullData;
                }
                result = new OfLotteryDetailResult()
                {
                    Code = RecCode,
                    Msg = Common.GetDescription((ResultCode)RecCode),
                    Data = RecCode != (int)ResultCode.Success ? null : Entity
                };
            }
            catch (Exception ex)
            {
                log.Write("开奖详情[OfLotteryDetail]：" + ex.StackTrace, true);
                result = new OfLotteryDetailResult()
                {
                    Code = (int)ResultCode.SystemBusy,
                    Msg = Common.GetDescription(ResultCode.SystemBusy),
                    Data = null
                };
            }
            return result;
        }

        /// <summary>
        /// 追号期次查询
        /// </summary>
        /// <param name="Token"></param>
        /// <param name="LotteryCode"></param>
        /// <param name="Top"></param>
        /// <returns></returns>
        public ChaseIsuseNumResult ChaseIsuseNum(int LotteryCode, int Top)
        {
            ChaseIsuseNumResult result = null;
            try
            {
                List<ChaseIsuseNumEntity> data = new List<ChaseIsuseNumEntity>();
                var Entitys = this.QueryChaseTasksIsuses(Top, LotteryCode);
                if (Entitys != null && Entitys.Count > 0)
                    data = this.QueryChaseTasksIsuses(Top, LotteryCode).Select(s => new ChaseIsuseNumEntity()
                    {
                        IsuseCode = s.IsuseID,
                        IsuseNum = s.IsuseName,
                        BeginTime = s.StartTime.ToString("yyyyMMddHHmmss"),
                        EndTime = s.EndTime.ToString("yyyyMMddHHmmss")
                    }).ToList();
                result = new ChaseIsuseNumResult()
                {
                    Code = (int)ResultCode.Success,
                    Msg = Common.GetDescription(ResultCode.Success),
                    Data = data
                };
            }
            catch (Exception ex)
            {
                log.Write("追号期次查询错误[ChaseIsuseNum]：" + ex.StackTrace, true);
                result = new ChaseIsuseNumResult()
                {
                    Code = (int)ResultCode.SystemBusy,
                    Msg = Common.GetDescription(ResultCode.SystemBusy)
                };
            }
            return result;
        }

        /// <summary>
        /// 开奖redis
        /// </summary>
        /// <param name="LotteryCode"></param>
        /// <param name="IsuseName"></param>
        /// <param name="LotteryWinNum"></param>
        /// <param name="StartTime"></param>
        /// <param name="EndTime"></param>
        /// <param name="LotteryTime"></param>
        /// <returns></returns>
        public bool InsertIsuseInfoRedis(int LotteryCode, string IsuseName, string LotteryWinNum, DateTime StartTime, DateTime EndTime, DateTime LotteryTime, long WinRollover, long TotalSales)
        {
            try
            {
                #region 检查
                OfLotteryDetailEntity DetailEntity = new BusinessRedis().OfLotteryDetailRedis(LotteryCode, IsuseName);
                if (DetailEntity != null)
                    return false;
                #endregion
                #region 开奖详情
                DetailEntity = new OfLotteryDetailEntity()
                {
                    LotteryCode = LotteryCode,
                    IsuseNum = IsuseName,
                    OpenTime = LotteryTime.ToString("yyyyMMddHHmmss"),
                    OpenNumber = LotteryWinNum,
                    WinRollover = WinRollover,
                    TotalSales = TotalSales
                };
                new BusinessRedis().OfLotteryDetailRedis(DetailEntity);
                #endregion
                #region 开奖列表
                OfLotteryEntity ofEntity = new OfLotteryEntity()
                {
                    IsuseNum = IsuseName,
                    LotteryCode = LotteryCode,
                    Number = LotteryWinNum,
                    OpenTime = LotteryTime == null ? DateTime.Now.ToString("yyyyMMddHHmmss") : LotteryTime.ToString("yyyyMMddHHmmss")
                };
                new BusinessRedis().OfLotteryRecordRedis(ofEntity);
                #endregion
                #region 方案详情
                var SchemeEntity = new SchemesBLL().QueryEntity(LotteryCode, IsuseName);
                foreach (var item in SchemeEntity)
                {
                    SchemeDetailEntity SchemeDetail = new BusinessRedis().SchemeDetailRedis(item.InitiateUserID, item.SchemeID);
                    if (SchemeDetail != null)
                    {
                        SchemeDetail.OpenNumber = LotteryWinNum;
                        new BusinessRedis().SchemeDetailRedis(item.InitiateUserID, item.SchemeID, SchemeDetail);
                    }
                }
                #endregion
                #region 发送开奖数据到IM
                var LotteryEntity = new LotteriesBLL().QueryEntity(LotteryCode);
                new IM.Communication().Send_Api_Issue(LotteryEntity.ChatRooms, LotteryCode, IsuseName, LotteryWinNum);
                #endregion
                return true;
            }
            catch (Exception ex)
            {
                log.Write("开奖数据插入redis[InsertIsuseInfoRedis]：" + ex.StackTrace, true);
                return false;
            }
        }
        /// <summary>
        /// 更新彩种期号奖等数据
        /// </summary>
        /// <param name="LotteryCode"></param>
        /// <param name="IsuseName"></param>
        /// <param name="WinRollover"></param>
        /// <param name="TotalSales"></param>
        /// <param name="Entitys"></param>
        public void ModifyIsuseInfoRedis(int LotteryCode, string IsuseName, long WinRollover, long TotalSales, List<DataAwardEntity> Entitys)
        {
            try
            {
                OfLotteryDetailEntity DetailEntity = new BusinessRedis().OfLotteryDetailRedis(LotteryCode, IsuseName);
                if (DetailEntity == null)
                    return;
                DetailEntity.WinRollover = WinRollover;
                DetailEntity.TotalSales = TotalSales;
                DetailEntity.DataAward = Entitys;
                new BusinessRedis().OfLotteryDetailRedis(DetailEntity);
            }
            catch (Exception ex)
            {
                log.Write("开奖数据更新redis[ModifyIsuseInfoRedis]：" + ex.StackTrace, true);
                return;
            }
        }
        /// <summary>
        /// 查询期次信息
        /// </summary>
        /// <param name="IsuseID"></param>
        /// <returns></returns>
        public string QueryIssueName(long IsuseID)
        {
            try
            {
                string IsuseName = new BusinessRedis().QueryIssueNameRedis(IsuseID);
                if (string.IsNullOrEmpty(IsuseName))
                {
                    IsuseName = this.QueryEntity(IsuseID).IsuseName;
                    new BusinessRedis().IssueNameRedis(IsuseID, IsuseName);
                }
                return IsuseName;
            }
            catch (Exception ex)
            {
                log.Write("查询期次信息[QueryIssueName]：" + ex.Message, true);
                return string.Empty;
            }
        }

        /// <summary>
        /// 开奖大厅
        /// </summary>
        /// <param name="Token"></param>
        /// <returns></returns>
        public OfLotteryResult OpenAwardHall(string Token)
        {
            OfLotteryResult result = null;
            try
            {
                result = new OfLotteryResult()
                {
                    Code = (int)ResultCode.Success,
                    Msg = Common.GetDescription(ResultCode.Success),
                    Data = this.OpenAwardHall().Select(s => new OfLotteryEntity()
                    {
                        IsuseNum = s.IsuseName,
                        Number = s.OpenNumber,
                        LotteryCode = s.LotteryCode,
                        OpenTime = s.OpenTime == null ? null : Convert.ToDateTime(s.OpenTime).ToString("yyyyMMddHHmmss")
                    }).ToList()
                };
            }
            catch (Exception ex)
            {
                log.Write("开奖大厅错误错误[OpenAwardHall]：" + ex.StackTrace, true);
                result = new OfLotteryResult()
                {
                    Code = (int)ResultCode.SystemBusy,
                    Msg = Common.GetDescription(ResultCode.SystemBusy)
                };
            }
            return result;
        }
        #endregion
    }
}
